package com.example.clienteclinicav2;

import java.io.IOException;
import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import org.xmlpull.v1.XmlPullParserException;

import com.example.clienteclinicav2.ListarClienteActivity.MyAdapter;
import com.example.clienteclinicav2.ListarClienteActivity.Node;
import com.example.clienteclinicav2.ListarClienteActivity.ObtenerPacientesBackground;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class ListarRegistroActivity  extends ListActivity {

	//definir estrutura de la lista
	public class Node{
		public String idRegistro;
		public String rutPaciente;
		public String diagnostico;
		public String fecha;
		public String idPrestacion;
		public String descripcion;
	}
	
	private static ArrayList<Node>mArray = new ArrayList<ListarRegistroActivity.Node>();
	private MyAdapter mAdapter = null;
	private String URL = "http://192.168.0.12:8080/ServicioPrestacionesClinica/services/RegistroORM";
	private String NAMESPACE = "http://capaservicio";

	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mArray.clear();
        new ObtenerRegistrosBackground().execute();
    }
	
	public void carga()
	{
		mAdapter = new MyAdapter(this);
        this.setListAdapter(mAdapter);
	}
	
	protected void onListItemClick(ListView l,View v, int position, long id){
		//pasar a la otra activity
		
		Intent iniciarActividad = new Intent(this, ModificarRegistroActivity.class );
		iniciarActividad.putExtra("idPrestacion", mArray.get(position).idPrestacion);
		iniciarActividad.putExtra("idRegistro", mArray.get(position).idRegistro);
		iniciarActividad.putExtra("fecha", mArray.get(position).fecha);
		iniciarActividad.putExtra("rut", mArray.get(position).rutPaciente);
		iniciarActividad.putExtra("diagnostico", mArray.get(position).diagnostico);
        startActivity(iniciarActividad);  
		
	}
	
	public class MyAdapter extends BaseAdapter
	{

		private Context mContext;
		
		public MyAdapter(Context c){
			Log.i("adapter", "cargando contexto");
			mContext = c;
		}
		public int getCount() {
			// TODO Auto-generated method stub
			return mArray.size();
		}
		public Object getItem(int posicion) {
			// TODO Auto-generated method stub
			return mArray.get(posicion);
		}
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return 0;
		}
		
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			View view = null;
			
			if(convertView==null){
				//Log.i("adapter", "null view");
				LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				view = inflater.inflate(R.layout.activity_listar_registro, null);
			}else{
				Log.i("adapter", "view");
				view = convertView;	
			}
			Log.i("adapter", "Cargando listado");
			TextView title = (TextView) view.findViewById(R.id.rutPaciente);
			title.setText(mArray.get(position).rutPaciente);
			
			TextView Tdesciption = (TextView) view.findViewById(R.id.diagnostico);
			Tdesciption.setText(mArray.get(position).diagnostico);
			
			return view;
		}
		
	}	
	
	 class ObtenerRegistrosBackground extends AsyncTask<Void, Void, String>{
	    	
	    	private ProgressDialog progressDialog;

			@Override
			protected void onPreExecute() {
	    		progressDialog = ProgressDialog.show(
	    				ListarRegistroActivity.this,
	    				"Prescli V1.0", 
	    				"Espere mientras se cargan los pacientes...", 
	    				true);
				super.onPreExecute();
			}

			@Override
			protected String doInBackground(Void... params) {

				String resultadoJSON="";
		    	String METHOD_NAME = "enviarListadoRegistros";
		    	String SOAP_ACTION = NAMESPACE +"/" +METHOD_NAME;
				SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
				SoapSerializationEnvelope soapEnvelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
				soapEnvelope.dotNet = true;
				soapEnvelope.implicitTypes =true;
				soapEnvelope.setOutputSoapObject(request);

				HttpTransportSE aht = new HttpTransportSE(URL);
				Log.d("Pacientes SOAP", "Iniciando Consulta");
				try {
					aht.call(SOAP_ACTION, soapEnvelope);
					SoapPrimitive resultString = (SoapPrimitive)soapEnvelope.getResponse();
					resultadoJSON = resultString.toString();
					Log.d("Pacientes SOAP", "Finalizando Consulta");
					
				} catch (IOException e) {
					e.printStackTrace();
				} catch (XmlPullParserException e) {
					e.printStackTrace();
				}
		    
				return resultadoJSON;
			}

			@Override
			protected void onPostExecute(String result) {
				super.onPostExecute(result);
				progressDialog.dismiss();
				if("".equals(result)){
					Toast.makeText(ListarRegistroActivity.this, "Error al obtener la informacion necesaria", Toast.LENGTH_LONG).show();
				}else{
					try {
						Log.i("mensaje", "llego al onpost");
						JSONArray peliculasJSONArray = new JSONArray(result);
						int cantPeliculas = peliculasJSONArray.length();
						for(int i = 0; i< cantPeliculas; i ++){
								Node mynode = new Node();
								mynode.diagnostico = peliculasJSONArray.getJSONObject(i).getString("diagnostico");
								mynode.idPrestacion  = peliculasJSONArray.getJSONObject(i).getString("idPrestacion");
								mynode.rutPaciente = peliculasJSONArray.getJSONObject(i).getString("rut");
								mynode.fecha = peliculasJSONArray.getJSONObject(i).getString("fecha");
								mynode.idRegistro = peliculasJSONArray.getJSONObject(i).getString("idRegistro");
								mynode.descripcion = peliculasJSONArray.getJSONObject(i).getString("descripcionPrestacion");
								mArray.add(mynode);
						}
						  carga();
					} catch (JSONException e) {
						Toast.makeText(ListarRegistroActivity.this, "2.Error al obtener la informacion necesaria", Toast.LENGTH_LONG).show();
					}
				}
			}
	    }
}
